<template>
  <!--
临建设施维修记录表 -->
  <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="editModel == 0 ? {} : rules" :class="editModel == 0 ? '' : 'rulesForm'">
      <!-- 表格 -->
      <a-card :bordered="false">
        <title-name title="临建设施维修记录表"></title-name>

        <custom-form :formList="formList" :form="form" :is-emit="false" :editModel="editModel == 0 ? '' : ''">
          <template v-slot:table>
                   <div>
          <a-button type="primary" @click="addLine" :disabled="editModel == 0">增行</a-button>
          <a-button @click="delLine" style="margin-left: 20px" :disabled="editModel == 0">删除行</a-button>
        </div>
            <a-form-model-item class="formTable" label=" " :colon="false">
              <a-table :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" ref="formTable" bordered :columns="columns" :data-source="form.list" :pagination="false">
                <template v-for="col in ['name', 'model', 'unit', 'quantity','sort']" :slot="col" slot-scope="text, record">
                  <div :key="col" class="form-item">
                    <template>
                      <template>
                        <!-- <a-input-number :min="0" v-if="col === 'quantity'" v-model="record[col]" :disabled="editModel == 0"></a-input-number> -->
                         <span v-if="col === 'sort'">{{record[col]}}</span>
                        <BaseInput  :maxLength='300'  v-else v-model="record[col]" :disabled="editModel == 0"></BaseInput>
                      </template>
                    </template></div
                ></template>
              </a-table>
            </a-form-model-item>
          </template>
        </custom-form>
      </a-card>
  </a-form-model>
   
</template>

<script>
import { querySchemeTemporaryFacilitiesLedgerDetail,batchUpdateSchemeTemporaryFacilitiesMaintain} from '@/api/project/plannManagement/maintenanceRecord.js' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import { isNull } from './model.js'

const columns = [
   {title: '序号',width: 80,dataIndex: 'sort',align: 'center'},
  { title: '名称', dataIndex: 'name', align: 'center', scopedSlots: { customRender: 'name' } },
  { title: '规格型号', dataIndex: 'model', align: 'center', scopedSlots: { customRender: 'model' } },
  { title: '单位', dataIndex: 'unit', align: 'center', scopedSlots: { customRender: 'unit' } },
  { title: '数量', dataIndex: 'quantity', align: 'center', scopedSlots: { customRender: 'quantity' } }
]
export default {
  name: 'maintenanceRecord' + Date.now(),
  extends: new BaseEditPage(),
  props: {
    statusBasicSuc: {
      type: Boolean,
      default: () => {}
    }
  },
  data() {
    return {
      columns,
      loading: false, // 加载控件
      editModel: 1, // 操作状态:0 查看;1 编辑
      planId: null,
      selectedRowKeys: [],
      tableData:[{sort:1,name: null,model: null,unit: null,quantity: null}],
      form: {
        list: []
      }, // 表单
      id: '',
      rules: {
        facilitiesType: [{ required: true, message: '请输入设施类型' }],
        serialNumber: [{ required: true, message: '请输入现场编号' }],
        maintenancePlace: [{ required: true, message: '请输入维保地点' }],
        maintenanceDate: [{ required: true, message: '请选择维保日期', trigger: 'change' }],
        content: [{ required: true, message: '请输入维修保养内容' }],
        }, // 校验规则
      init: false // 初始化控件
    }
  },
 watch: {
  statusBasicSuc: {
      handler(val, oldVal) {
        let form = this.$clone(this.form)
        form.status = this.status
        form.schemeDetailId = this.id
        form.changed = this.pageType == 'change' ? true : false // 是编辑还是变更
        val && this.statusBasicSucFn(form);
      },
      deep: true
    }
  },
  created() {
  },
  async mounted() {
    await this.getDetailData()
  },
  computed: {
    formList() {
      return [
        {
          keyName: 'facilitiesType',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '设施类型'
        },
        {
          keyName: 'serialNumber',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '现场编号'
        },
        {
          keyName: 'maintenancePlace',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '维保地点'
        },
         {
          keyName: 'maintenanceDate',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          disabled: this.editModel == 0,
          label: '维保日期',
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'content',
          type: 'BaseTextarea',
          label: '维修保养内容',
          disabled: this.editModel == 0,
          span: 24,
          attrs: {
            maxLength: 3000
          }
        },
        {
          slot: true,
          customItemSlot: true,
          keyName: 'table',
          span: 24,
           attrs: {
            maxLength: 3000
          }
        }
      ]
    }
  },
  methods: {
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    //添加行
    addLine() {
      this.form.list.push({
        name: null,
        model: null,
        unit: null,
        quantity: null,
        sort: this.form.list.length + 1
      })
    },
    delLine() {
      let that = this
      if (!this.selectedRowKeys.length) {
        this.$message.warning('请选择要删除的数据')
        return false
      }
      this.$confirm({
        okText: '确认',
        cancelText: '取消',
        title: '提示?',
        content: `请确认是否要删除?`,
        onOk() {
          that.sureDel()
        },
        onCancel() {}
      })
    },
    sureDel() {
      if (this.selectedRowKeys.length) {
        this.selectedRowKeys.map((item) => {
          delete this.form.list[item]
        })
      }
      this.selectedRowKeys = []
      let filterBlankArr = this.form.list.filter((item) => item) //过滤数组空白的数据
      this.form.list = filterBlankArr
    },
    validateForm() {
      let flag = false
      this.$refs.ruleForm.validate((e) => {
        if (e) {
          flag = true
        }else {
          this.$message.warning('请填写完所有必填项信息')
        }
      })
      return flag
    },
     getDetailData() {
      // 不为添加时请求详情
       this.$emit('update:spinning', true)
         let reqObj = {
          schemeDetailId: this.id,
          latestData:true
        }
        if (this.version) {
          reqObj.version = this.version,
          reqObj.latestData = false
        }
        querySchemeTemporaryFacilitiesLedgerDetail(reqObj)
          .then((res) => {
           this.$emit('update:spinning', false)
            this.form = { ...this.form, ...res.data }
            if (!this.form.list || !this.form.list.length) {
              this.form.list = this.tableData
            }
          })
          .catch(() => {
            this.$emit('update:spinning', false)
          })
    },
    /**
     * 提交表单
     */
    maintenanceRecordSubmit(baseData) {
      let dataDable = this.form.list
      if (!dataDable.length) {
        this.$message.warning('请至少填写一行数据')
        return
      } else {
        let rulesArr = []
        dataDable.map((item) => {
          let a = Object.values(item).every((oItem) => isNull(oItem))
          a && rulesArr.push(a)
        })
        let flag = rulesArr.length === dataDable.length
        if (!flag) {
          this.$message.warning('请完善表格数据')
          return
        }
      }
      if (!this.validateForm()) {
        return
      }
      this.sure(1,baseData)
    },
    sure(str,baseData) {
      let that = this
      this.$confirm({
        okText: '确认',
        cancelText: '取消',
        title: '提交?',
        content: `请确认是否要提交?`,
        onOk() {
          that.submitFn(str,baseData)
        },
        onCancel() {}
      })
    },
    maintenanceRecordSaveDrafts(baseData) {
      //保存草稿
      this.submitFn(0,baseData)
    },

    submitFn(status, baseData) {
      this.$emit('update:spinning', true)
      baseData.schemeDetailId = this.id
      baseData.status = status
      this.status = status;
      this.$emit('updateBasicDetail', baseData)
    },
    statusBasicSucFn(formData){
        let msg = this.status * 1 === 1 ? '提交' : '保存草稿'
        let api = batchUpdateSchemeTemporaryFacilitiesMaintain
        api(formData).then(() => {
            this.$emit('update:spinning', false)
            this.$message.success(`${msg}成功！`)
            this.status * 1===1 && this.$multiTab.close()
        })
        .catch(() => {
          this.$message.warning(err.data.message)
          this.$emit('update:spinning', false)
        })
    }
  }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
.scene {
  display: block;
  margin: 10px 0 10px 60px;
  color: rgba(0, 0, 0, 0.85);
}
.rulesForm {
  @{deep} .ant-input,
  @{deep} .ant-input-model-input,
  @{deep} .ant-input-number-input,
  @{deep} .ant-select .ant-select-selection {
    border-color: #e4ac0b;
    background-color: #fff9e8;
  }
  @{deep} .mandatory .ant-input {
    border-color: #d9d9d9;
    background-color: #fff;
  }
  @{deep} .setPlaceholder {
    .ant-select-selection__placeholder {
      display: block !important;
    }
  }
}
@{deep} .formTable {
  .ant-form-item-label {
    width: 0;
  }
  .ant-form-item-control-wrapper {
    width: 100%;
  }
}
</style>
